package display.android.fyales.com.displaytime;

import android.app.Service;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.IBinder;
import android.support.annotation.Nullable;

import java.util.Calendar;

/**
 * @author fyales
 * @since 2017/10/16
 */

public class ScreenService extends Service {

    private long mAllTime;   //一天亮屏的总时间
    private long mStartTime;  //开始时间
    private long mStopTime;   //开屏时间

    private Calendar mCalendar;
    private static ScreenService mInstance;

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        return START_STICKY;
    }

    @Override
    public void onCreate() {
        super.onCreate();

        mInstance = this;

        ScreenObserverReceiver receiver = new ScreenObserverReceiver();
        IntentFilter filter = new IntentFilter();
        filter.addAction(Intent.ACTION_SCREEN_ON);
        filter.addAction(Intent.ACTION_SCREEN_OFF);
        registerReceiver(receiver,filter);

        mCalendar = Calendar.getInstance();
        mStartTime = System.currentTimeMillis();

        new Thread(new Runnable() {
            @Override
            public void run() {
                while (true){
                    if (isNewDay()){
                        mAllTime = 0;
                    }
                }
            }
        }).start();
    }

    public void setStartTime(){
        mStartTime = System.currentTimeMillis();
    }

    public void setCloseTime(){
        mStopTime = System.currentTimeMillis();
        if (mStopTime > mStartTime){
            long value = mStartTime - mStopTime;
            mAllTime += value;
        }
    }

    public long getAllTime() {
        return mAllTime;
    }

    /**
     * 如果是新一天的开始，就返回true
     * @return
     */
    private boolean isNewDay(){
        int hour = mCalendar.get(Calendar.HOUR_OF_DAY);
        int minute = mCalendar.get(Calendar.MINUTE);
        int seconds = mCalendar.get(Calendar.SECOND);
        int mileSeconds = mCalendar.get(Calendar.MILLISECOND);

        if (hour == 0 && minute == 0 && seconds == 0 && mileSeconds == 0){
            return true;
        }

        return false;
    }

    public static ScreenService getInstance(){
        return mInstance;
    }
}
